import { createStore, createLogger } from 'vuex';
import api from '@/api';

const env = process.env.NODE_ENV;
const store = createStore({
    state: {
        isLogin: null,
        info: null,
        storeList: null
    },
    mutations: {
        // 同步修改登录状态
        changeIsLogin(state, bool) {
            state.isLogin = bool;
        },
        // 同步修改登录者信息
        changeInfo(state, info) {
            state.info = info;
        },
        // 同步收藏列表
        queryStoreList(state, list) {
            state.storeList = list;
        },
        // 移除收藏列表中的某一项
        removeStoreList(state, id) {
            if (!state.storeList) return;
            state.storeList = state.storeList.filter(item => +item.id !== +id);
        }
    },
    actions: {
        // 异步修改登录状态
        async changeIsLoginAsync({ commit }) {
            let { code, data } = await api.checkLogin();
            if (+code !== 0) {
                // 登录失败
                commit('changeIsLogin', false);
                return false;
            }
            // 登录成功
            commit('changeIsLogin', true);
            commit('changeInfo', data);
            return true;
        },
        // 异步修改登录者信息
        async changeInfoAsync({ commit }) {
            let { code, data } = await api.userInfo();
            if (+code !== 0) return null;
            commit('changeInfo', data);
            return data;
        },
        // 异步从服务器获取收藏列表
        async queryStoreListAsync({ commit }) {
            let { code, data } = await api.storeList();
            if (+code !== 0) data = [];
            commit('queryStoreList', data);
            return data;
        }
    },
    plugins: env !== "production" ? [createLogger()] : []
});
export default store;